package com.lanchewuyou.user.driver.yancheui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.modul.Config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * 上传照片页面(单独使用)
 */
public class YancheChoosePhoActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton yancheChooseBack;
    private ImageView img;
    private Button yancheChoosePhoto, yancheUploadPhoto;
    private TextView yancheChooseTitle;
    private static String DRIVERID;
    private String imgUrl;

    private static int CHOOSEPHOTOREQUEST = 1;
    private String PERSON_PHOTO_FOLDER = new File(Environment.getExternalStorageDirectory(), "").getPath() + "/lanchewuyou/person/";

    private Toast toast = null;

    private void showTextToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yanche_choose_pho);
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file1 = new File(PERSON_PHOTO_FOLDER);
            if (!file1.exists()) {
                file1.mkdir();
            } else {
                Log.d("path", "exists");
            }
        } else {
            showTextToast("请确认已经插入SD卡");
        }
        initViews();

    }

    private void initViews() {
        yancheChooseBack = (ImageButton) findViewById(R.id.yanche_choose_photo_back);
        yancheChooseBack.setOnClickListener(this);
        img = (ImageView) findViewById(R.id.yanche_choose_photo_img);
        img.setOnClickListener(this);
        yancheChoosePhoto = (Button) findViewById(R.id.yanche_choose_photo_choose);
        yancheChoosePhoto.setOnClickListener(this);
        yancheUploadPhoto = (Button) findViewById(R.id.yanche_choose_photo_upload);
        yancheUploadPhoto.setOnClickListener(this);
        yancheChooseTitle=(TextView)findViewById(R.id.yanche_choose_type_title);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.yanche_choose_photo_back:
                finish();
                break;
            case R.id.yanche_choose_photo_img:
                Intent intent=new Intent(YancheChoosePhoActivity.this,YanchePhotoActivity.class);
                intent.putExtra("yancheimgurl",imgUrl);
                startActivity(intent);
                break;
            case R.id.yanche_choose_photo_choose:
                startPhoActivity();
                break;
            case R.id.yanche_choose_photo_upload:

                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        String path1 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS).get(0);

                        Bitmap bitmap = getBitmapFromFile(path1);
                        bitmap = resizeBitmap(bitmap, 600);
                        //saveBitmap(bitmap, saveName + "1");
                    }
                }
                break;
            default:
                break;
        }
    }

    private void startPhoActivity() {
        PhotoPickerIntent intent1 = new PhotoPickerIntent(YancheChoosePhoActivity.this);
        intent1.setPhotoCount(1);
        intent1.setShowCamera(true);
        startActivityForResult(intent1, CHOOSEPHOTOREQUEST);
    }

    /**
     * 保存图片到具体位置
     *
     * @param bitmap
     */
    public void saveBitmap(Bitmap bitmap, String saveName) {
        File f = new File(PERSON_PHOTO_FOLDER, saveName + ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 固定宽度压缩图片
     *
     * @param bitmap
     * @param newWidth
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float temp = ((float) height) / ((float) width);
        int newHeight = (int) ((newWidth) * temp);
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        // resize the bit map
        matrix.postScale(scaleWidth, scaleHeight);
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        //bitmap.recycle();
        return resizedBitmap;
    }

    /**
     * 从存储路径获取bitmap
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmapFromFile(String filePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        return bitmap;
    }

}
